import './index.scss'
import { Card, Form, Input, Button, message } from 'antd'

import logo from '@/assets/logo.png'
import { fetchLogin } from '@/store/modules/user'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { useState } from 'react'

const Login = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const user = useSelector((state) => state.user)
  // 展示登录状态
  const [isLoading, setIsLoading] = useState(false)

  // 点击登录按钮时触发 参数values即是表单输入数据
  const onFinish = async (values) => {
    try {
      // console.log(values)
      // 触发异步action fetchLogin
      setIsLoading(true)
      const token = await dispatch(fetchLogin(values))
      // 1. 跳转到首页
      // 2. 提示登录成功
      if (token) {
        navigate('/')
        message.success('登录成功')
      }
    } catch (error) {
      console.log(error)

      message.error('登录失败')
    } finally {
      // 无论成功与否都要关闭loading
      setIsLoading(false)
    }
  }
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form onFinish={onFinish}>
          <Form.Item label="手机号" name="mobile">
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item label="验证码" name="code">
            <Input size="large" placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              {isLoading ? '登录中...' : '登录'}
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
